package tx.bj12320.util;

import java.util.Collection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;



/**
 * SpringSecurity的工具类.
 *
 */
public class SpringSecurityUtils {
	protected static Log log = LogFactory.getLog("SpringSecurityUtils");

	/**
	 * 是否为匿名用户
	 * @return
	 */
	public static boolean isAnonymousUser(){
		return getCurrentUserName().equals("anonymousUser");
	}
	/**
	 * 取得当前用户的登录名, 如果当前用户未登录则返回空字符串.
	 */
	public static String getCurrentUserName() {
		/*
		UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
	    .getAuthentication()
	    .getPrincipal();
	out.println(userDetails.getUsername());
	out.println(userDetails.getAuthorities().toString());
	*/
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
//		log.info(auth);
		if (auth == null) {
//			log.info("null");
			return "";
		}else{
			Object p=SecurityContextHolder.getContext()
		    .getAuthentication()
		    .getPrincipal();
			if(p instanceof String){
				return p.toString();
			}else{
				return ((UserDetails)p).getUsername();
			}

		}


	}
	/**
	 * 得到当前用户授权角色
	 * @return
	 */
	public static String getCurrentUserRole() {

		String role="";
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if (auth == null) {
			return "";
		}else{
			Object p=SecurityContextHolder.getContext()
		    .getAuthentication()
		    .getPrincipal();
			if(p instanceof String){
				return p.toString();
			}else{
				Collection<GrantedAuthority> gs=((UserDetails)p).getAuthorities();
				for (GrantedAuthority grantedAuthority : gs) {
					role= grantedAuthority.getAuthority();
				}

			}

		}
		return role;


	}

	/**
	 * 取得当前用户, 返回值为SpringSecurity的User类及其子类, 如果当前用户未登录则返回null.
	 */
	@SuppressWarnings("unchecked")
	public static <T extends User> T getCurrentUser() {
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if (principal == null) {
			return null;
		}
		return (T) principal;
	}
}
